package com.yzt.zhuju.base;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yzt.zhuju.R;
import com.yzt.zhuju.application.BaseAct;
import com.yzt.zhuju.event.BaseBusEvent;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.zhuju.widget.ProgressDialog;
import com.yzt.p_base.AppUtils;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.p_base.utils.KeyboardUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.p_base.utils.TLogManager;
import com.yzt.p_base.utils.ToastUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public abstract class BaseActivity extends BaseAct {

    private static final String TAG_MODULE = "life cycle";

    public final static int PAGE_SIZE = 20;

    public int mCurrentPage = 1;

    private ProgressDialog mProgressDialog;

    protected Handler mHandler;

    private final List<Subscription> mSubscriptions = new ArrayList<>();

    public boolean isDark;

    public void showToast(String tip) {
        ToastUtil.showMessage(tip);
    }

    public void refreshScreen() {

    }

    private static class MyHandler extends Handler {
        WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }
    }

    private String getTopActivityName() {
        if (ActivityManagerUtils.getInstance() != null
                && ActivityManagerUtils.getInstance().getActivity() != null
                && ActivityManagerUtils.getInstance().getActivity().getClass() != null
                && ActivityManagerUtils.getInstance().getActivity().getClass().getSimpleName() != null) {
            return ActivityManagerUtils.getInstance().getActivity().getClass().getSimpleName();
        } else {
            return "BaseActivity";
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TLogManager.loge(TAG_MODULE, getTopActivityName(), "生命周期  ------  onCreate");
        mHandler = new MyHandler(this);
        ARouter.getInstance().inject(this);
        setFullScreen(false, R.color.transparent);
        setContentView(getLayoutId());
        installViews();
        keyboardHeight();

        // 设置长亮
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public int keyHeight = 0;

    protected void keyboardHeight() {
        KeyboardUtils.registerSoftInputChangedListener(mActivity, height -> {
            mSoftInputHeight(height);
            if (height > keyHeight) {
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.KEYBOARD_HEIGHT, height);
                keyHeight = height;
            }
        });
    }

    public void mSoftInputHeight(int height) {

    }

    protected <E extends BaseBusEvent> void observerRxBus(Class<E> busClass, Action1<E> onNext) {
        Subscription subscription = RxBus.getDefault().observerRxBus(busClass, onNext);
        mSubscriptions.add(subscription);
    }

    protected <E extends BaseBusEvent> void observerRxBusSticky(Class<E> busClass, Action1<E> onNext) {
        Subscription subscription = RxBus.getDefault().observerRxBusSticky(busClass, onNext);
        mSubscriptions.add(subscription);
    }

    @Override
    protected void onResume() {
        TLogManager.loge(TAG_MODULE, getTopActivityName(), "生命周期  ------  onResume");
        super.onResume();
    }

    @Override
    protected void onPause() {
        TLogManager.loge(TAG_MODULE, getTopActivityName(), "生命周期  ------  onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        TLogManager.loge(TAG_MODULE, getTopActivityName(), "生命周期  ------  onDestroy");
        super.onDestroy();
        for (Subscription subscription : mSubscriptions) {
            if (subscription == null) {
                continue;
            }
            if (subscription.isUnsubscribed()) {
                continue;
            }
            subscription.unsubscribe();
        }
        mSubscriptions.clear();
        mHandler.removeCallbacksAndMessages(null);
        KeyboardUtils.unregisterSoftInputChangedListener(this);
    }

    /**
     * 设置状态栏颜色
     */
    public void setStatusBarColor(int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(mActivity, colorId));
        }
        mStatusBarLayout.setVisibility(View.GONE);
    }

    public void hindBottomBar() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        getWindow().setAttributes(params);
    }

    /**
     * 侵入式状态栏
     *
     * @param isHideStatuHeight true：整个布局侵入状态栏   false：预留状态栏的高度，颜色为白色，可以设置其他颜色
     */
    public void setFullScreen(boolean isHideStatuHeight, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }

        View decor = mActivity.getWindow().getDecorView();
        if (isDark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        if (isHideStatuHeight) {
            mStatusBarLayout.setVisibility(View.GONE);
        } else {
            mStatusBarLayout.setBackgroundColor(ContextCompat.getColor(mActivity, color));
            mStatusBarLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 侵入式状态栏
     *
     * @param isHideStatuHeight true：整个布局侵入状态栏   false：预留状态栏的高度，颜色为白色，可以设置其他颜色
     */
    public void setFullScreen(boolean isHideStatuHeight) {
        setFullScreen(isHideStatuHeight, R.color.white);
    }

    /**
     * 状态栏字体颜色
     */
    public void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = mActivity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 显示进度
     */
    public void showMProgress() {

        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }

        mProgressDialog.setShowContent("");

        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    /**
     * 显示进度
     */
    public void showMProgress(String msg) {

        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(false);
        }

        if (!mProgressDialog.isShowing()) {
            mProgressDialog.setShowContent(msg);
            mProgressDialog.show();
        }
    }

    /**
     * 关闭progress提示框
     */
    public void closeProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.cancel();
        }
    }

    public abstract int getLayoutId();

    public abstract void installViews();

    public View getErrorView(String text) {
        return getEmptyView(R.mipmap.icon_network_error, text);
    }

    public View getEmptyView() {
        return getEmptyView(R.mipmap.icon_empty_data, getString(R.string.page_empty));
    }

    public View getEmptyView(String text) {
        return getEmptyView(R.mipmap.icon_empty_data, text);
    }

    public View getEmptyView(int imageId, String text) {
        if (mActivity == null) {
            return new View(AppUtils.getContext());
        }
        View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_empty_view, null);
        ImageView emptyImage = view.findViewById(R.id.iamge_empty);
        TextView emptyText = view.findViewById(R.id.text_empty);
        emptyImage.setImageResource(imageId);
        emptyText.setText(text);
        return view;
    }

    @Override
    public void finish() {
        super.finish();
        VoicePlayManager.getInstance().stopPlay();
    }

    @Override
    protected void onStop() {
        TLogManager.loge(TAG_MODULE, getTopActivityName(), "生命周期  ------  onStop");
        super.onStop();
        closeProgress();
    }
}
